﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;
using System.Runtime.InteropServices;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using ESPlus.Rapid;
using GG.Core;
using ESBasic.ObjectManagement.Forms;
using ESPlus.Application.P2PSession.Passive;
using ESPlus.FileTransceiver;
using ESBasic;
using ImageCapturerLib;
using OMCS.Passive;
using GGLib;
using GGLib.NDisk.Passive;
using ESBasic.ObjectManagement.Managers;

namespace GG
{
    public partial class GroupChatForm : CCSkinMain ,IManagedForm<string>
    {
        private Group currentGroup;
        private EmotionForm emotionForm;
        private IRapidPassiveEngine rapidPassiveEngine;
        private GlobalUserCache globalUserCache;
        private User currentUser;    
       
        #region IManagedForm Member
        public string FormID
        {
            get { return this.currentGroup.ID; }
        } 
        #endregion

        #region Ctor
        public GroupChatForm(IRapidPassiveEngine engine, Group group, GlobalUserCache cache)
        {
            this.rapidPassiveEngine = engine;
            this.currentGroup = group;
            this.globalUserCache = cache;
            this.currentUser = this.globalUserCache.GetUser(this.rapidPassiveEngine.CurrentUserID);

            InitializeComponent();

            //添加表示不在线的灰度图            
            for (int i = 0; i < 10; i++)
            {
                this.imageList2.Images.Add(ESBasic.Helpers.ImageHelper.ConvertToGrey(this.imageList2.Images[i]));
            }

            this.Text = string.Format("{0}({1})",this.currentGroup.Name ,this.currentGroup.ID);
            this.labelFriendName.Text = this.currentGroup.Name;     
            this.textBoxSend.Focus();

            List<Image> emotionList = new List<Image>();
            foreach (Image emotion in this.imageList1.Images)
            {
                emotionList.Add(emotion);
            }

            this.emotionForm = new EmotionForm();
            this.emotionForm.Load += new EventHandler(emotionForm_Load);
            this.emotionForm.Initialize(emotionList);
            this.emotionForm.EmotionClicked += new ESBasic.CbGeneric<Image>(emotionForm_Clicked);
            this.emotionForm.Visible = false;

            int onlineCount = 0;
            foreach (string memberID in group.Members)
            {
                User user = this.globalUserCache.GetUser(memberID);              
                ListViewItem item = this.listView1.Items.Add(string.Format("{0}({1})", user.Name, memberID));
                item.ImageIndex = user.Online ? user.HeadImageIndex : 10 + user.HeadImageIndex;
                item.Tag = user;
                if (user.Online)
                {
                    ++onlineCount;
                }
            }

            this.skinTabControl1.TabPages[0].Text = string.Format("群成员({0}/{1})", onlineCount, group.Members.Count);
        }        

        void emotionForm_Load(object sender, EventArgs e)
        {
            this.emotionForm.Location = new Point((this.Left + 30) - (this.emotionForm.Width / 2), this.Top + this.skinPanel_left.Top + skToolMenu.Top - this.emotionForm.Height);
        }

        void emotionForm_Clicked(Image img)
        {
            this.textBoxSend.InsertImage(img);
            this.emotionForm.Visible = false;
        } 
        #endregion       

        #region TabControlContains
        private bool TabControlContains(string text)
        {
            for (int i = 0; i < this.skinTabControl1.TabPages.Count; i++)
            {
                if (this.skinTabControl1.TabPages[i].Text == text)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion

        #region GetSelectIndex
        private int GetSelectIndex(string text)
        {
            for (int i = 0; i < this.skinTabControl1.TabPages.Count; i++)
            {
                if (this.skinTabControl1.TabPages[i].Text == text)
                {
                    return i;
                }
            }
            return -1;
        }
        #endregion               

        public void GroupmateStateChanged(string userID, bool online)
        {
            foreach (ListViewItem item in this.listView1.Items)
            {
                User user = (User)item.Tag ;
                if (user.ID == userID)
                {
                    item.ImageIndex = online ? user.HeadImageIndex : 10 + user.HeadImageIndex;
                    break;
                }
            }

            int onlineCount = 0;
            foreach (string memberID in this.currentGroup.Members)
            {
                User user = this.globalUserCache.GetUser(memberID);               
                if (user.Online)
                {
                    ++onlineCount;
                }
            }

            this.skinTabControl1.TabPages[0].Text = string.Format("群成员({0}/{1})", onlineCount, this.currentGroup.Members.Count);
        }

        #region OnSomeoneJoin
        public void OnSomeoneJoin(string userID)
        {           
            User user = this.globalUserCache.GetUser(userID);
            ListViewItem item = this.listView1.Items.Add(string.Format("{0}({1})", user.Name, userID));
            item.ImageIndex = user.Online ? user.HeadImageIndex : 10 + user.HeadImageIndex;
            item.Tag = user;

            int onlineCount = 0;
            foreach (string memberID in this.currentGroup.Members)
            {
                User member = this.globalUserCache.GetUser(memberID);
                if (member.Online)
                {
                    ++onlineCount;
                }
            }

            this.skinTabControl1.TabPages[0].Text = string.Format("群成员({0}/{1})", onlineCount, this.currentGroup.Members.Count);
            this.AppendSysMessage(string.Format("{0}({1})加入了该群！", user.Name, user.ID));
        }
        #endregion

        #region OnSomeoneQuit
        public void OnSomeoneQuit(string userID)
        {           
            User user = this.globalUserCache.GetUser(userID);
            ListViewItem target = null;
            foreach (ListViewItem item in this.listView1.Items)
            {
                if (item.Tag == user)
                {
                    target = item;
                    break;
                }
            }
            this.listView1.Items.Remove(target);

            int onlineCount = 0;
            foreach (string memberID in this.currentGroup.Members)
            {
                User member = this.globalUserCache.GetUser(memberID);
                if (member.Online)
                {
                    ++onlineCount;
                }
            }

            this.skinTabControl1.TabPages[0].Text = string.Format("群成员({0}/{1})", onlineCount, this.currentGroup.Members.Count);
            this.AppendSysMessage(string.Format("{0}({1})退出了该群！", user.Name, user.ID));
        }
        #endregion

        #region 文字聊天
        #region FlashChatWindow
        [DllImport("User32")]
        public static extern bool FlashWindow(IntPtr hWnd, bool bInvert);
        public void FlashChatWindow()
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                int MyTimes = 4;
                int MyTime = 500;
                for (int MyCount = 0; MyCount < MyTimes; MyCount++)
                {
                    FlashWindow(this.Handle, true);
                    System.Threading.Thread.Sleep(MyTime);
                }
            }
            else
            {
                this.Show();
                this.Focus();
            }
        }
        #endregion

        #region 发送
        //发送
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (this.textBoxSend.Text == "")
            {
                return;
            }

            try
            {
                byte[] buff = System.Text.Encoding.UTF8.GetBytes(this.textBoxSend.Rtf);
                this.rapidPassiveEngine.GroupOutter.BroadcastBlob(this.currentGroup.ID, BroadcastTypes.BroadcastChat, buff ,2048 ,null);
                this.AppendMessage(string.Format("{0}({1})" ,this.currentUser.Name,this.currentUser.ID), RtfRichTextBox.RtfColor.Green, this.textBoxSend.Rtf, true);

                //清空输入框
                this.textBoxSend.Text = string.Empty;
                this.textBoxSend.Focus();
            }
            catch
            {
                this.rtfRichTextBox_history.AppendText(DateTime.Now.ToLongTimeString() + " 发送消息失败！");
            }
        }
        #endregion

        #region AppendMessage
        private void AppendMessage(string userName, RtfRichTextBox.RtfColor color, string msg, bool isRtf)
        {
            DateTime showTime = DateTime.Now;
            this.rtfRichTextBox_history.AppendTextAsRtf(string.Format("{0}  {1}\n", userName, showTime), new Font(this.Font, FontStyle.Regular), color);

            if (isRtf)
            {
                this.rtfRichTextBox_history.AppendRtf(msg);
            }
            else
            {
                this.rtfRichTextBox_history.AppendText(msg);
            }
            this.rtfRichTextBox_history.Select(this.rtfRichTextBox_history.Text.Length, 0);
            this.rtfRichTextBox_history.ScrollToCaret();
        }

        public void AppendSysMessage(string msg)
        {
            this.AppendMessage("系统", RtfRichTextBox.RtfColor.Gray, msg, false);
            this.rtfRichTextBox_history.AppendText("\n");
        }
        #endregion

        #region 字体
        //显示字体对话框
        private void toolFont_Click(object sender, EventArgs e)
        {
            this.fontDialog1.Font = this.textBoxSend.Font;
            this.fontDialog1.Color = this.textBoxSend.ForeColor;
            if (DialogResult.OK == this.fontDialog1.ShowDialog())
            {
                this.textBoxSend.Font = this.fontDialog1.Font;
                this.textBoxSend.ForeColor = this.fontDialog1.Color;
            }
        }
        #endregion        

        public void OnReceivedMsg(string userID ,string msg)
        {
            User user = this.globalUserCache.GetUser(userID);
            string talker = string.Format("{0}({1})", userID, userID);
            if (user != null)
            {
                talker = string.Format("{0}({1})", user.Name, user.ID);
            }
            this.AppendMessage(talker, RtfRichTextBox.RtfColor.Blue, msg, true);
        }

        
        #endregion

        #region 窗体事件
        //悬浮至好友Q名时
        private void labelFriendName_MouseEnter(object sender, EventArgs e)
        {
            this.labelFriendName.Font = new Font("微软雅黑", 14F, FontStyle.Underline);
        }

        //离开好友Q名时
        private void labelFriendName_MouseLeave(object sender, EventArgs e)
        {
            this.labelFriendName.Font = new Font("微软雅黑", 14F);
        }

        //渐变层
        private void FrmChat_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            SolidBrush sb = new SolidBrush(Color.FromArgb(100, 255, 255, 255));
            g.FillRectangle(sb, new Rectangle(new Point(1, 91), new Size(Width - 2, Height - 91)));
        }

        //窗体调用重绘时
        protected override void OnInvalidated(InvalidateEventArgs e)
        {
            rtfRichTextBox_history.Invalidate();
            textBoxSend.Invalidate();
            base.OnInvalidated(e);
        }

        private void ChatForm_SizeChanged(object sender, EventArgs e)
        {
            this.skinPanel_left.Height = this.Height - 100;
        }
        
        #endregion      

        #region 关闭窗体
        //关闭
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ChatForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.emotionForm.Visible = false;
            this.emotionForm.Close();           
            e.Cancel = false;
        } 
        #endregion

        #region 截图
        private void buttonCapture_Click(object sender, EventArgs e)
        {
            ImageCapturer imageCapturer = new ImageCapturer();
            if (imageCapturer.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.textBoxSend.InsertImage(imageCapturer.Image);
                this.textBoxSend.Focus();
                this.textBoxSend.ScrollToCaret();
            }
        } 
        #endregion       

        #region 表情
        private void toolStripButtonEmotion_Click(object sender, EventArgs e)
        {
            this.emotionForm.Location = new Point((this.Left + 30) - (this.emotionForm.Width / 2), this.Top + this.skinPanel_left.Top + skToolMenu.Top - this.emotionForm.Height);
            this.emotionForm.Visible = !this.emotionForm.Visible;
        } 
        #endregion

        #region 手写板
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            PaintForm form = new PaintForm();
            form.Location = new Point(this.Left + 20, this.Top + this.skinPanel_left.Top + skToolMenu.Top - form.Height);
            if (DialogResult.OK == form.ShowDialog())
            {
                Bitmap bitmap = form.CurrentImage;
                if (bitmap != null)
                {
                    this.textBoxSend.InsertImage(bitmap);
                    this.textBoxSend.Focus();
                    this.textBoxSend.ScrollToCaret();
                }
            }
        } 
        #endregion        
    }
}
